package com.shoppingmall.controller.portal;

import com.shoppingmall.common.GuavaCache;
import com.shoppingmall.common.ServletResponse;
import com.shoppingmall.pojo.User;
import com.shoppingmall.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by touni on 2019/3/18 12:56
 *
 * 用户管理模块  主要用于登录修改密码等操作
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 存储用户的session的名称
     */
    @Value("${USER_SESSION}")
    private String userSessoin;

    /**
     * 用户忘记密码后更改密码需要携带的token
     */
    @Value("${USER_FORGETTOKEN}")
    private String USER_FORGETTOKEN;

    /**
     * 用户登录模块
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ServletResponse<User> userLogin(String username, String password, HttpSession session){
        ServletResponse<User> userServletResponse = userService.userLogin(username, password);
        session.setAttribute(userSessoin,userServletResponse.getData());
        return userServletResponse;

    }

    @RequestMapping(value="/register",method = RequestMethod.POST)
    public ServletResponse userRegister(User user){
        return userService.userRegister(user);


    }

    /**
     * 默认情况下检查用户名是否存在
     * 可以更改type的值来查询email是否存在
     * @param value
     * @return
     */
    @RequestMapping(value = "/check_username",method = RequestMethod.POST)
    public ServletResponse checkUsername(String value, @RequestParam(value = "type",defaultValue = "1") Integer type){

        return userService.checkValue(value,type);
    }

    /**
     * 获取用户的信息  默认从session中获取
     * 如果session没有则表示用户未登录
     * @param session
     * @return
     */
    @RequestMapping(value = "/get_user_info",method = RequestMethod.POST)
    public ServletResponse<User> getUserInfo(HttpSession session){
        User userFromSession = (User) session.getAttribute(userSessoin);
        if (null == userFromSession) {
            return ServletResponse.createByErrorcodeAndMessage(1,"用户未登录");
        }
        return ServletResponse.createBySuccess(userFromSession);
    }

    /**
     * 根据用户名查询这个用户的问题
     * @return
     *
     * tip 为提高安全性，此处可以直接在session中获取用户名，不用传参数
     */
    @RequestMapping(value = "/forget_get_question",method = RequestMethod.POST)
    public ServletResponse getUserQuestion(HttpSession session){
        // todo  这个方法可以进行改善  为了程序安全需要在这里使用session获取用户名
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("用户未登录，请先登录");
        }
        //先调用方法查询这个用户名是否存在
        ServletResponse<Integer> checkUsernameResponse = userService.checkValue(userFromSession.getUsername(), 1);
        if (checkUsernameResponse.getData() != 1){
            return ServletResponse.createByErrorMessage("用户名非法");
        }
        return userService.getUserQuestionByUsername(userFromSession.getUsername());
    }


    /**
     *通过回答问题来修改密码，此处选择在session中获取用户名
     * @return
     * 在此处生成guava缓存
     */
    @RequestMapping(value = "/forget_check_answer",method = RequestMethod.POST)
    public ServletResponse checkUserAnswer(HttpSession session,String question,String answer){
        User userFromSession = (User)session.getAttribute(userSessoin);
        //判断这个用户是否为空
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("用户未登录");
        }

        ServletResponse<User> servletResponse =
                userService.checkUserAnswer(userFromSession.getUsername(),question,answer);
        if (null == servletResponse.getData()){
            return servletResponse;

        }

        String tokenValue = UUID.randomUUID()+servletResponse.getData().getUsername();
        //将token放入缓存中
        GuavaCache.setKey(USER_FORGETTOKEN+servletResponse.getData().getUsername(),tokenValue);



        return ServletResponse.createBySuccess(tokenValue);
    }

    /**
     *
     * 根据token 用户名  新密码来更改密码
     * @param passwordNew
     * @return
     */
    @RequestMapping(value = "/forget_reset_password",method = RequestMethod.POST)
    public ServletResponse resetPasswordByAnswer(HttpSession session,String passwordNew,String forgetToken){
        //从session中获取用户名
        User userFromSession = (User)session.getAttribute(userSessoin);
        //判断这个用户是否为空
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("用户未登录");
        }
        //从guava缓存中获取token信息
        String cacheValue = GuavaCache.getKey(USER_FORGETTOKEN + userFromSession.getUsername());
        if (!StringUtils.equals(cacheValue,forgetToken)){

            return ServletResponse.createByErrorMessage("token过期，请重新修改密码");
        }
        //  每次修改成功密码后强制退出登录

        ServletResponse resultResponse = userService.resetPasswordByAnswer(userFromSession.getUsername(), passwordNew);
        if (resultResponse.isSuccess()){
            logout(session);

        }
        return resultResponse;



    }

    /**
     * 在登录的情形下修改密码   用户名从session中获取
     * @param passwod
     * @param passwordNew
     * @return
     */
    @RequestMapping(value = "/reset_password",method = RequestMethod.POST)
    public ServletResponse resetPasswordByPassword(String passwod,String passwordNew,HttpSession session){
        User userFromSession = (User)session.getAttribute(userSessoin);
        if (null  == userFromSession){

            return ServletResponse.createByErrorMessage("用户未登录，请先登录");
        }
        //  每次修改成功密码后强制退出登录
        ServletResponse resultResponse = userService.resetPasswordByPassword(userFromSession.getUsername(), passwod, passwordNew);
        if (resultResponse.isSuccess()){
            logout(session);

        }
        return resultResponse;


    }


    /**
     * 登录状态下修改用户的信息
     * @param email
     * @param phone
     * @param question
     * @param answer
     * @return
     */
    @RequestMapping(value = "/update_information",method = RequestMethod.POST)
    public ServletResponse updateUserInformation(HttpSession session,String email,String phone,String question,String answer){
        //首先验证是否登录
        User userFromSession = (User) session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("用户未登录，请先登录");
        }
        //校验email是否重复了
        ServletResponse<Integer> checkEmail = userService.checkValue(email, 2);
        if (1 == checkEmail.getData()){
            return ServletResponse.createByErrorMessage("email重复了，请输入其他的email");

        }

        return userService.updateUserInformation(userFromSession.getUsername(),email,phone,question,answer);



    }


    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public ServletResponse logout(HttpSession session){
        //从session中获取这个用户，并干掉
        User userFromSession = (User) session.getAttribute(userSessoin);
        if (null == userFromSession){
            return ServletResponse.createByErrorMessage("当前没有用户登录");
        }
        session.removeAttribute(userSessoin);
        return ServletResponse.createBySuccessMessage("用户退出成功");



    }


















}
